package com.imooc.controller;

import com.imooc.constant.CookieConstant;
import com.imooc.constant.RedisConstant;
import com.imooc.dataobject.SellerInfo;
import com.imooc.enums.ResultEnum;
import com.imooc.service.SellerInfoService;
import com.imooc.util.CookieUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Map;
import java.util.UUID;
import java.util.concurrent.TimeUnit;

/**
 * @author liuhuan
 * @date 2018/7/22 11:03
 * @description
 */
@Controller
@RequestMapping("sellerInfo")
public class SellerInfoController {

    @Autowired
    private SellerInfoService sellerInfoService;

    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    @GetMapping("login")
    public ModelAndView login(@RequestParam("openId") String openId, Map<String,Object> map,
                              HttpServletResponse response){
        //1.openid去和数据库去匹配
        SellerInfo sellerInfo=sellerInfoService.findSellerInfoByOpenId(openId);
        if(sellerInfo==null){
            map.put("msg", ResultEnum.LOGIN_FAIL.getMsg());
            map.put("url","sell/order/list");
            return new ModelAndView("common/error",map);
        }
        //2.设置token至redis
        String token= UUID.randomUUID().toString();
        stringRedisTemplate.opsForValue().set(String.format(RedisConstant.TOKEN_PROFIX,token),openId,RedisConstant.EXPIRE, TimeUnit.SECONDS);

        //3.设置token至cookie
        CookieUtil.set(response, CookieConstant.COOKIR_NAME,token,RedisConstant.EXPIRE);
        return new ModelAndView("redirect:sell/order/list");

    }
    @GetMapping("logout")
    public ModelAndView logout(HttpServletRequest request,
                       HttpServletResponse response,
                       Map<String,Object> map){
        //1.从cookie查询
        Cookie cookie=CookieUtil.get(request,CookieConstant.COOKIR_NAME);
        if(cookie!=null){
            //2.清除reids

            stringRedisTemplate.opsForValue().getOperations().delete(String.format(RedisConstant.TOKEN_PROFIX,cookie.getValue()));
            //3.清除cookie
            CookieUtil.set(response,CookieConstant.COOKIR_NAME,null,0);
        }
        map.put("msg",ResultEnum.LOGOUT.getMsg());
        map.put("url","sell/order/list");
        return new ModelAndView("common/success",map);

    }
}
